<?php

function echoJsonResponse($success, $url = "", $message = "", $javascript = "", $errors = array(), $extraData = array()){

	$ajaxRequest = getInput("ajaxRequest",false);

	//var_dump($_REQUEST);
	if($ajaxRequest){
		$json = new stdClass();
		$json->success = $success;
		$json->url = $url;
		$json->javascript = $javascript;
		if(!$success){
			if(isset($_SESSION['ERRORMESSAGE'])){
				$message = $_SESSION['ERRORMESSAGE'] .$message ;
				$_SESSION['ERRORMESSAGE'] = "";
			}
		}

		// this is bacuse the javascript that gets this response breaks with the chars < >
		$json->message = str_replace("<br/>", "\n",$message);
		$json->message = str_replace("<", "{_less_}",$json->message);
		$json->message = str_replace(">", "{_greater_}",$json->message);

		$json->errors = $errors;

		if(!empty($extraData)){
			foreach ($extraData as $key => $value){
				$json->$key = $value;
			}
		}

		echo json_encode($json);
		exit;
	}else{
		if($message){
			if(!$success){
				logError($message);
			}else{
				logSuccess($message);
			}
		}
		if($url != "")
			forward($url);
		else
			forward($_SERVER["HTTP_REFERER"]);
	}
}
